<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

const chartRef = ref(null);

// 格式化时间戳为 YYYY-MM-DD HH:mm 的形式
const formatDateTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

onMounted(() => {
  const chart = echarts.init(chartRef.value);

  const fetchDataAndUpdateChart = async () => {
    try {
      const response = await axios.get('http://localhost:8085//SoilN//tenSoilNdata');
      const data = response.data;

      const timeData = data.map(item => formatDateTime(item.createTime));
      const NData = data.map(item => item.dataValue);

      const option = {
        title: {
          text: '土壤含氮量浓度随时间变化',
          left: 'center',
          textStyle: {
            color: '#FFFFFF',
          },
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b0}: {c0} ppm',
        },
        xAxis: {
          type: 'category',
          data: timeData,
          axisLabel: {
            rotate: 45,
            color: '#FFFFFF',
          },
          axisLine: {
            lineStyle: {
              color: '#FFFFFF',
            },
          },
          axisTick: {
            show: true,
            lineStyle: {
              color: '#FFFFFF',
            },
          },
        },
        yAxis: {
          type: 'value',
          name: 'N含量(mg/kg)',
          axisLabel: {
            color: '#FFFFFF',
          },
          axisLine: {
            lineStyle: {
              color: '#FFFFFF',
            },
          },
          axisTick: {
            show: true,
            lineStyle: {
              color: '#FFFFFF',
            },
          },
        },
        series: [
          {
            name: 'N含量mg/kg',
            type: 'line',
            data: NData,
            smooth: true,
            itemStyle: {
              color:  '#1E90FF',
            },
            lineStyle: {
              width: 2,
            },
          },
        ],
        grid: {
          left: '10%',
          right: '10%',
          bottom: '10%',
          top: '20%',
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
          },
        ],
      };

      chart.setOption(option);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };

  fetchDataAndUpdateChart();
  setInterval(fetchDataAndUpdateChart, 300000); // 每5分钟更新一次数据
});
</script>

<template>
  <dv-border-box10>
    <div ref="chartRef" style="width: 430px; height: 210px;margin-left: 20px;margin-top: 10px"></div>
  </dv-border-box10>
</template>

<style scoped>

</style>